<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" :label-position="'top'">
      <el-row>
        <el-col :span="8">
          <el-form-item label="订单号" prop="orderNo">
            <el-input v-model="form.orderNo" placeholder="自动生成" :readonly="true" maxlength="30" style="width: 90%"/>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="订单名称" prop="orderName">
            <el-input v-model="form.orderName" placeholder="请输入订单名称" maxlength="50" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="供应商" prop="supplierCode">
            <el-select v-model="form.supplierCode" placeholder="请选择供应商" filterable clearable @change="changeData" style="width: 90%">
              <el-option
                v-for="dict in supplierList"
                :key="dict.value"
                :label="dict.label"
                :value="dict"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人" prop="contactId">
            <el-select v-model="form.contactId" placeholder="请选择联系方式" clearable style="width: 90%" >
              <el-option
                v-for="dict in contactList"
                :key="dict.code"
                :label="dict.label+'('+dict.code+')'"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="金额" >
            <el-input v-model="form.orderAmount" :readonly="true" placeholder="自动生成" maxlength="30" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="制单人" >
            <el-input v-model="name" placeholder="自动生成" :readonly="true" maxlength="30" style="width: 90%"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>订单明细信息</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="openProductDialog">新增</el-button>
          </div>
          <el-table :data="orderDetails">
            <el-table-column label="商品名称" align="center" key="productName" prop="productName" />
            <el-table-column label="商品编码" align="center" key="productCode" prop="productCode" />
            <el-table-column label="规格" align="center" key="specUnit" prop="specUnit" />
            <el-table-column label="单位" align="center" key="productUnit" prop="productUnit" />
            <el-table-column label="单价(元)" align="center" key="orderPrice" prop="orderPrice" />
            <el-table-column label="数量" align="center" key="num">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.num" @change="culAmount(scope)" :min="1" />
              </template>
            </el-table-column>
            <el-table-column label="总价(元)" align="center" key="totalAmount" prop="totalAmount" />
            <el-table-column
              label="操作"
              align="center"
              width="160"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="delOrderDetail(scope)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row>
            <el-col :span="24" style="text-align: center;margin-top: 20px">
              <el-button type="primary" @click="saveOrder" >提交</el-button>
              <el-button @click="addCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog :title="'添加商品'" :visible.sync="addOpen" width="500px" append-to-body>
      <el-form ref="tempForm" :model="tempForm" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品" prop="productCode">
              <el-select v-model="tempForm.productCode"
                         style="width: 100%"
                         filterable
                         remote
                         reserve-keyword
                         :remote-method="getProducts"
                         :loading="productLoading"
                         placeholder="请选择商品"
                         clearable>
                <el-option
                  v-for="dict in productList"
                  :key="dict.value"
                  :label="dict.productName"
                  :value="dict"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="单价" prop="orderPrice">
              <el-input v-model="tempForm.orderPrice" placeholder="请输入单价" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="数量" prop="num">
              <el-input-number v-model="tempForm.num" style="width: 100%" :min="1" ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="addOpen =false ">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDictList } from "@/api/wms/supplier";
import { addObj } from "@/api/wms/purchase";
import { getDictList as getContactDict} from "@/api/wms/contact";
import { getProductList } from "@/api/wms/product";
import { mapGetters } from 'vuex'

export default {
  name: "createOrder",
  data() {
    return {
      // 订单表单
      form: {
        contactId: undefined,
        orderAmount: 0,
        orderNo: undefined,
        orderName: undefined,
        supplierCode: undefined
      },
      // 表单参数
      addOpen: false,
      // 产品加载等待
      productLoading: false,
      // 可编辑单元格
      cellIndex: null,
      // 供应商
      supplierList: [],
      // 产品
      productList: [],
      // 联系人
      contactList: [],
      // 订单详情
      orderDetails: [],
      // 添加商品临时表单
      tempForm:{
        orderPrice: undefined,
        num: undefined,
        productCode: undefined
      },
      // 表单校验
      rules: {
        orderPrice: [
          { required: true, message: "单价不能不能为空", trigger: "blur" }
        ],
        num: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        productCode: [
          { required: true, message: "商品不能为空", trigger: ['change'] },
        ]
      }
    };
  },
  created() {
    this.getSupplierList();
  },
  computed: {
    ...mapGetters([
      'name'
    ]),
  },
  methods: {
    saveOrder(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form['list'] = this.orderDetails
          this.form['supplierCode'] = this.form.supplierCode.value
          addObj(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.$router.push("/purchase/order");
          });
        }
      })
    },
    addCancel(){
      this.$router.push("/purchase/order");
    },
    culAmount({$index, row}){
      row.totalAmount = row.orderPrice*row.num

      let orderAmount = 0;
      this.orderDetails.forEach((item,index)=>{
        orderAmount += item.num * item.orderPrice
      })
      this.form.orderAmount = orderAmount
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["tempForm"].validate(valid => {
        if (valid) {
          const has = this.orderDetails.filter(item => item.productCode === this.tempForm.productCode.productCode).length > 0;
          if(has){
            this.$modal.msgError("请勿重复添加商品");
          }else{
            this.addOpen = false
            this.orderDetails.push({
              productCode: this.tempForm.productCode.productCode,
              productName: this.tempForm.productCode.productName,
              num: this.tempForm.num,
              orderPrice: this.tempForm.orderPrice,
              productUnit: this.tempForm.productCode.productUnit,
              specUnit: this.tempForm.productCode.specUnit,
              totalAmount: this.tempForm.num * this.tempForm.orderPrice,
            })
            this.form.orderAmount = this.form.orderAmount + this.tempForm.num * this.tempForm.orderPrice
            this.resetTempForm()
          }
          // this.resetTempForm()
        }
      });
    },
    resetTempForm(){
      this.tempForm = {
        orderPrice: undefined,
        num: undefined,
        productCode: undefined
      };
      this.resetForm("tempForm");
    },
    openProductDialog(){
      this.addOpen = true
    },
    getProducts(query){
      if(query!==''){
        this.productLoading = true
        getProductList({keyword: query}).then(response => {
          this.productList = response.data
          this.productLoading = false
        });
      }else{
        this.productList=[]
      }
    },
    delOrderDetail({$index, row}){
      this.orderDetails.splice($index, 1);
      this.form.orderAmount = this.form.orderAmount - row.num * row.orderPrice
    },
    /** 查询用户列表 */
    getSupplierList() {
      getDictList().then(response => {
          this.supplierList = response.data
        }
      );
    },
    getContactList(sid){
      getContactDict(sid).then(response => {
          this.contactList = response.data
        }
      );
    },
    changeData(value){
      this.form.contactId = undefined
      this.getContactList(value.code)
    }
  }
}
</script>

<style scoped>

</style>
